package com.celeritymq.connection;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import javax.jms.ConnectionConsumer;
import javax.jms.JMSException;
import javax.jms.ServerSessionPool;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicSession;

import com.celeritymq.session.CelerityTopicSession;

public class CelerityTopicConnection extends CelerityConnectionImpl implements TopicConnection {
	private CelerityConnectionConsumer durableConnectionConsumer;
	private List<CelerityTopicSession> sessionList = new ArrayList<CelerityTopicSession>();
	private List<CelerityConnectionConsumer> consumerList = new ArrayList<CelerityConnectionConsumer>();

	CelerityTopicConnection(SocketAddress address, int bufferSize) throws IOException, SecurityException,
			IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException,
			InvocationTargetException, InterruptedException {
		super(address, bufferSize);
	}

	@Override
	public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool serverSessionPool,
			int maxMessages) throws JMSException {
		CelerityConnectionConsumer consumer = new CelerityConnectionConsumer(topic, messageSelector, serverSessionPool,
				maxMessages);
		consumerList.add(consumer);
		return consumer;
	}

	// topic - the topic to access
	// messageSelector - only messages with properties matching the message
	// selector expression are delivered. A value of null or an empty string
	// indicates that there is no message selector for the message consumer.
	// sessionPool - the server session pool to associate with this connection
	// consumer
	// maxMessages - the maximum number of messages that can be assigned to a
	// server session at one time
	@Override
	public synchronized ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName,
			String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
		if (durableConnectionConsumer == null) {
			durableConnectionConsumer = new CelerityConnectionConsumer(topic, subscriptionName, messageSelector, sessionPool,
					maxMessages);
		}
		return durableConnectionConsumer;
	}

	@Override
	public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException {
		CelerityTopicSession session = new CelerityTopicSession(targetAddress, transacted, acknowledgeMode);
		sessionList.add(session);
		return session;
	}

}
